{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Python 模块"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "python模块是一个比较常用的功能，模块类似于Java中的jar包，是一个将部分程序功能通过打包的形式包装成一个整体的形式，然后便于我们在需要使用的场景直接通过引用模块来实现功能，降低代码的耦合性，增加代码的复用性。模块的使用可以通过使用**from**关键字和**import**关键字,如下给出一个简单的小例子:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "system path: ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.7/dist-packages/IPython/extensions', '/home/caihaifei/.ipython']\n",
      "Tue Dec  5 13:17:53 2017\n",
      "\n",
      "\n",
      "[4, 5, 0, 3, 8, 1, 9, 6, 2, 7]\n",
      "deque([45, 4, 5, 0, 3, 8, 1, 9, 6, 2, 7])\n",
      "deque([0, 3, 8, 1, 9, 6, 2, 7, 45, 4, 5])\n"
     ]
    }
   ],
   "source": [
    "#通过import直接导入模块.\n",
    "import sys,time\n",
    "#通过from module import  function 导入random 模块中的shuffle函数.\n",
    "from random import shuffle\n",
    "#通过from module import * 导入collections模块的所有公开API.\n",
    "from collections import *\n",
    "\n",
    "\n",
    "#导入的sys模块的特性使用\n",
    "print \"system path:\",sys.path\n",
    "print time.asctime()\n",
    "#导入的shuffle的使用，shuffle可以将序列随机打乱\n",
    "list=[1,2,3,4,5,6,7,8,9,0]\n",
    "shuffle(list)\n",
    "print \"\\n\\n\",list\n",
    "#导入的collection模块\n",
    "q=deque(list)\n",
    "q.append(12)\n",
    "q.appendleft(45)\n",
    "q.pop()\n",
    "print q\n",
    "q.rotate(-3)\n",
    "print q "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如上为简单使用的几个python自带的模块的使用示例。其中导入的模块之间或者模块的属性之间可以通过***，**来连接.通过**import**直接导入的模块使用其内部的属性或函数等的时候需要使用**moduleName.beahavior**来调用，而通过**from moudle import name**  方式调用的模块可以直接通过属性名称使用而不需要指定模块名称.如下，通过几个方面来了解模块的使用以及创建。\n",
    "\n",
    "- [模块的创建](#1)\n",
    "- [包与模块](#2)\n",
    "- [模块中的一些魔法属性以及模块的使用说明](#3)\n",
    "- [python中的自带常用模块的使用](#4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"1\">模块的创建</a>\n",
    "\n",
    "\n",
    "模块的创建其实就是创建一个py文件，让其可以通过在py文件中定义一些诸如“类、属性、函数\"等，然后通过在另一个脚本文件(*.py)中导入执行或者直接通过命令行命令执行。如下根据一个简单的示例来介绍模块的创建过程.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#caculator.py\n",
    "\n",
    "#!/usr/bin/env python\n",
    "# -*- encoding:utf-8 -*-\n",
    "\n",
    "import sys\n",
    "\n",
    "def addition(*args):\n",
    "    \"\"\"\n",
    "    Addition Operation.\n",
    "    :param args:  All the operands.\n",
    "    :return: the result of operation.\n",
    "    \"\"\"\n",
    "    if len(args) > 0:\n",
    "        result = args[0]\n",
    "        try:\n",
    "            for operand in args[1:]:\n",
    "                result += operand\n",
    "        except Exception as e:\n",
    "            print str(e)\n",
    "            pass\n",
    "        return result\n",
    "    else:\n",
    "        print \"args must not be empty.\"\n",
    "        raise Exception(\"args must not be empty.\")\n",
    "\n",
    "\n",
    "def subtraction(*args):\n",
    "    \"\"\"\n",
    "    Subtraction Operation.\n",
    "    :param args: All the operands.\n",
    "    :return: the result of operation.\n",
    "    \"\"\"\n",
    "    if len(args) > 0:\n",
    "        result = args[0]\n",
    "        try:\n",
    "            for operand in args[1:]:\n",
    "                result -= operand\n",
    "        except Exception as e:\n",
    "            print str(e)\n",
    "            pass\n",
    "        return result\n",
    "    else:\n",
    "        print \"args must not be empty.\"\n",
    "        raise Exception(\"args must not be empty.\")\n",
    "\n",
    "\n",
    "def monocular(operator, *args):\n",
    "    \"\"\"\n",
    "     Simple Operation\n",
    "    :param operator:  Operator for monocular operations\n",
    "    :param args: All the operands.\n",
    "    :return:the result of operation.\n",
    "    \"\"\"\n",
    "    if len(args) > 0:\n",
    "         result = float(args[0])\n",
    "        try:\n",
    "            for operand in args[1:]:\n",
    "                if operator in \"+\":\n",
    "                    result += float(operand)\n",
    "                elif operator in '-':\n",
    "                    result -= float(operand)\n",
    "                elif operator in '*':\n",
    "                    result *= float(operand)\n",
    "                elif operator in '/':\n",
    "                    result /= float(operand)\n",
    "        except Exception as e:\n",
    "            print str(e)\n",
    "            pass\n",
    "        return result\n",
    "    else:\n",
    "        print \"args must not be empty.\"\n",
    "        raise Exception(\"args must not be empty.\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    \"\"\"\n",
    "      By  external call.\n",
    "    \"\"\"\n",
    "    print \"main step.\"\n",
    "    # args of used.\n",
    "    if len(sys.argv) >= 4:\n",
    "        print sys.argv\n",
    "        args = sys.argv[1:]\n",
    "        result = monocular(args[0], *(args[1:]))\n",
    "         print \"get result:\", result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15\n"
     ]
    }
   ],
   "source": [
    "import calculator,sys\n",
    "\n",
    "#设置模块文件加载的路径\n",
    "sys.path.append('../')\n",
    "print calculator.monocular(\"/\",46,3)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如上，为一个简单的单目计算器，提供了单独的计算加法、减法和通过指定运算符号（\"+\"、“-”、“*”、“/”）来计算结果，如上所示。通过**import**导入caculator可以直接使用calculator中的计算方法。**caculator**中页提供了直接传入参数的方法，使用如下:\n",
    "\n",
    "```\n",
    "caihaifei@hfcai:#  python calculator.py - 12 4\n",
    "['calculator.py', '-', '12', '4']\n",
    "get result: 8.0\n",
    "\n",
    "\n",
    "```\n",
    "\n",
    "\n",
    "如上,通过命令行传入参数,py中通过导入sys模块，对输入参数通过sys.args进行接收,接受对象为一个list,将参数依照顺传入，然后对参数进行过滤处理，参数参数，回调返回运算结果."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"2\">包与模块</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"3\">模块中的一些魔法属性以及模块的使用说明</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"4\">python中的自带常用模块的使用</a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
